/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 * <p>
 * SdProjectMilepostService 项目策划-里程碑
 * <p>
 * 修改纪录 2021-12-20 版本：1.0 hdy 创建。
 *
 * @version 版本：1.0
 * @author 作者：hdy 创建日期：2021-12-20
 */
package com.topscomm.gpm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.gpm.pojo.*;
import com.topscomm.gpm.pojo.GpmProjectMilepostEntity;
import com.topscomm.gpm.GpmSystemConst;
import com.topscomm.mis.constant.MisSystemConst;
import com.topscomm.mis.mobile.message.service.SendMessageService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.topscomm.gpm.utils.MessageUtil;
import com.topscomm.tap.common.DatacodeCache;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.gpm.service.IGpmProjectMilepostService;
import com.topscomm.gpm.service.impl.auto.GpmProjectMilepostServiceAuto;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service(value = "gpmProjectMilepostService")
@Scope(value = "singleton")
public class GpmProjectMilepostService extends GpmProjectMilepostServiceAuto implements
        IGpmProjectMilepostService {

    @Autowired
    private GpmProjectPlanService gpmProjectPlanService;

    @Autowired
    private GpmProjectTaskService gpmProjectTaskService;

    @Autowired
    private GpmMilePostTemplateService gpmMilePostTemplateService;

    @Autowired
    private GpmProjectService gpmProjectService;
    @Autowired
    private GpmProjectTaskTemplateService gpmProjectTaskTemplateService;
    @Autowired
    private GpmProjectSuperviseService gpmProjectSuperviseService;
    @Autowired
    private DatacodeCache datacodeCache;
//    @Autowired
//    private ICboMessageAppService cboMessageAppService;
//    @Autowired
//    private ICboMessageSysService cboMessageSysService;
    @Autowired
    private SendMessageService sendMessageService;


    /**
     * @author: hdy
     * @date: 2021-12-20
     * @param: entity
     * @description:
     * @return: void
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) throws ServiceException {
        if (entity.getId() <= 0) {// 赋值Id和单号
            long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
            entity.setId(arrayId[0]);
            if ((Long) entity.getValue("operatecode") == 0) {
                entity.setValue("operatecode", arrayId[0]);
            }
            //设置用户添加里程碑赋值 sourcetype
            if(entity.getValue("sourcetype")==null){
                entity.setValue("sourcetype","user");
            }
            //新增  赋值
            long planid = ConvertUtil.convertToLong(entity.getValue("planid") );
            StringBufferProxy sql = new StringBufferProxy();
            GpmProjectPlanEntity gpmProjectPlanEntity = gpmProjectPlanService.queryById(ConvertUtil.convertToString(planid));
            entity.setValue(GpmProjectMilepostEntity.FieldProjectid, gpmProjectPlanEntity.getProjectid());
            entity.setValue(GpmProjectMilepostEntity.FieldDeptcommoncode1, gpmProjectPlanEntity.getDeptcommoncode1());

            String docNo = String.valueOf(arrayId[0]);
            docNo = docNo.substring(0, 6) + docNo.substring(9);
            entity.setValue(GpmProjectMilepostEntity.FieldMilepostcode, docNo);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date planfinishtime = null;
            if(entity.getValue("planfinishtime")!=null&&!"".equals(entity.getValue("planfinishtime"))){
                try {
                    planfinishtime = simpleDateFormat.parse(entity.getValue("planfinishtime").toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                    throw new MessageException("日期错误，请填写正确格式的日期！");
                }
                sql.clear();
                sql.appendSingle("projectcode = '{0}'",entity.getValue("projectcode"));
                List<GpmProjectEntity> sdProjectEntities = gpmProjectService.queryByWhere(sql.toString());
                Date planenddate = sdProjectEntities.get(0).getPlanenddate();
                Date planstartdate = sdProjectEntities.get(0).getPlanstartdate();
                if(planfinishtime.compareTo(planenddate)>0){
                    throw new MessageException("里程碑的计划达成时间不能大于所属项目的计划结束时间！");
                }
                if(planfinishtime.compareTo(planstartdate)<0){
                    throw new MessageException("里程碑的计划达成时间不能小于所属项目的计划开始时间！");
                }
            }
        }
    }

    @Override
    protected void afterInsert(BasicEntity entity) throws ServiceException {
        //刚插入的里程碑enabled置为0，审批技术后enabled置为1
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" id = '{0}'", entity.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("enabled", 0);
        this.updateByWhere(map, sql.toString());
    }

    @Override
    protected void afterInsertBatch(List<BasicEntity> listEntity) throws ServiceException {
        // 刚插入的里程碑enabled置为0，审批结束后enabled置为1
        String id = listEntity.stream().map(entity -> "'" + ConvertUtil.convertToString(entity.getId()) + "'")
                .collect(Collectors.joining(","));
        // 只有id不为空时才会执行update操作，防止sql报错
        if(!StringUtil.isEmpty(id)) {
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle(" id in ({0})", id);
            HashMap<String, Object> map = new HashMap<>();
            map.put("enabled", 0);
            this.updateByWhere(map, sql.toString());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    protected void deleteBefore(String whereSql) {
    	if(whereSql.contains("planid")) {
    		return;
    	}
        StringBufferProxy sql = new StringBufferProxy();
        String[] split = whereSql.split(" ");
        sql.appendSingle(" id  in {0} ", split[3]);
        List<GpmProjectMilepostEntity> gpmProjectMilepostEntityList = this
            .queryByWhere(sql.toString());
        sql.clear();
        StringBuffer string = new StringBuffer();
        for (GpmProjectMilepostEntity entity : gpmProjectMilepostEntityList
        ) {
            string.append(entity.getOperatecode());
            string.append(",");
        }
        String substring = string.substring(0, string.lastIndexOf(","));
        sql.appendSingle("milepostcode in ({0})", substring);
        List<GpmProjectTaskEntity> sdProjectTaskEntities = this.gpmProjectTaskService
            .queryByWhere(sql.toString());
        if (sdProjectTaskEntities.size() > 0) {
            String delStr = sdProjectTaskEntities.stream().map(item -> ConvertUtil.convertToString(item.getId())).collect(Collectors.joining(","));
            gpmProjectTaskService.deleteByIds(delStr);
        }
    }


    @Override
    protected void updateBefore(Map<String, Object> map) throws ServiceException {
        try{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendSingle("projectcode = '{0}'", map.get("projectcode"));
            List<GpmProjectEntity> sdProjectEntities = gpmProjectService.queryByWhere(sql.toString());
            if(sdProjectEntities.size()>0){
                Date planenddate = sdProjectEntities.get(0).getPlanenddate();
                Date planstartdate = sdProjectEntities.get(0).getPlanstartdate();
                Date miletime = simpleDateFormat.parse(map.get("planfinishtime").toString());
                if (miletime.compareTo(planenddate) > 0) {
                    throw new MessageException("里程碑的计划达成时间不能大于所属项目的计划结束时间！");
                }
                if(miletime.compareTo(planstartdate)<0){
                    throw new MessageException("里程碑的计划达成时间不能小于所属项目的计划开始时间！");
                }
            }
        }catch (ParseException e){
            e.printStackTrace();
            throw new MessageException("日期格式错误，请填写正确格式的日期！");
        }
    }
/**
  * @description:
  * @author hdy
  * @param
  * @throws
  * @return
  * @date 2021-12-20
  * @modify
  */
    @Transactional(rollbackFor = Exception.class)
    public void insertBatch(Map<String,Object> paraMap){

        //获取最新策划书id
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("enabled=1 and state = 0 and projectcode ='{0}' order by CREATEON desc",paraMap.get("projectcode"));
        List<GpmProjectPlanEntity> planNewEntities = gpmProjectPlanService
                .queryByWhere(sql.toString());
        sql.clear();
        //若获取不到策划书则直接返回
        if(planNewEntities.isEmpty()){
            return;
        }
        //若参数不为空，则为新策划书添加旧策划书里程碑信息
        if (!ConvertUtil.convertToString(paraMap.get("oldmilepost")).equals("[]") && paraMap.get("oldmilepost") != null) {
            List<GpmProjectMilepostEntity> datalist = JSON
                    .parseArray(ConvertUtil.convertToString(paraMap.get("oldmilepost")),
                            GpmProjectMilepostEntity.class);
            // operatecode 为当前策划书里程碑与旧策划书相同里程碑的共同字段
            sql.appendSingle("enabled=0 and planid= '{0}' and  operatecode='{1}' ",
                    planNewEntities.get(0).getId(), datalist.get(0).getOperatecode());
            List<GpmProjectMilepostEntity> milepostentites = this
                    .queryByWhere(sql.toString());
            // 若存在旧里程碑 且 新策划书未同步旧里程碑
            if (datalist.size() != 0 && milepostentites.size() < 1) {
                for (GpmProjectMilepostEntity data : datalist) {
                    data.setValue(GpmProjectMilepostEntity.FieldCopysourceid, data.getId());
                    data.setValue("id", "");
                    data.setNewadd(0);
                    data.setVersion(data.getVersion()+1);
                    // 同步的里程碑enabled值为0，当策划变更审批结束时enabled置为1
                    data.setEnabled(0);
                    data.setPlanid(planNewEntities.get(0).getId());
                    this.insert(data);
                }
            }
        }
    }
    /**
     * @param paraMap
     * @return
     * @Title: insert
     * @description:
     * @author: wudalaing
     * @date: 2021-12-20
     * @modify:
     */
    public ResponseResult insertFromProject(Map<String, Object> paraMap) {
        String projectcodeNew = (String) paraMap.get("projectcodenew");
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("projectcode = '{0}'", projectcodeNew);
        List<GpmProjectEntity> sdProjectEntities = this.gpmProjectService
            .queryByWhere(sql.toString());
        String ids = (String) paraMap.get("keys");
        if (!StringUtil.isEmpty(ids)) {
            List<GpmProjectMilepostEntity> gpmProjectMilepostEntityList = this.queryByIds(ids);
            for (GpmProjectMilepostEntity GpmProjectMilepostEntity : gpmProjectMilepostEntityList) {
                //赋值里程碑初始字段
                GpmProjectMilepostEntity.setId(0);
                GpmProjectMilepostEntity.setMilepoststate(0);
                GpmProjectMilepostEntity.setMilepostcode("");
                GpmProjectMilepostEntity.setState(0);
                GpmProjectMilepostEntity.setPlanfinishtime(null);
                GpmProjectMilepostEntity.setActualfinishtime(null);
                GpmProjectMilepostEntity.setResponsible("");
                GpmProjectMilepostEntity.setResponsiblecode("");
                GpmProjectMilepostEntity.setSourceid(sdProjectEntities.get(0).getId());
                GpmProjectMilepostEntity.setSourcetype("按项目添加");
                GpmProjectMilepostEntity.setDescription("");
                GpmProjectMilepostEntity.setOperatecode(0);
                GpmProjectMilepostEntity.setPlanid((long) paraMap.get("planid"));
                GpmProjectMilepostEntity.setProjectcode(projectcodeNew);
                this.insert(GpmProjectMilepostEntity);
            }
            return ResponseResult.ok("插入任务成功，共 " + gpmProjectMilepostEntityList.size() + "条。");
        } else {
            return ResponseResult.ok("没有可插入的任务数据，请确认勾选相关任务！");
        }
    }

    /**
     * @author: hdy
     * @date: 2021-12-20
     * @param: paraMap keys 模板对应id projectcode 项目编号 planid 策划书id
     * @description: 按照模板添加里程碑
     * @return: com.topscomm.pub.vo.ResponseResult
     * @modify:
     */
    public ResponseResult insertFromMilePostTemplate(Map<String, Object> paraMap) {
        String ids = ConvertUtil.convertToString(paraMap.get("keys"));
        String projectcode = ConvertUtil.convertToString(paraMap.get("projectcode"));
        String projectname = ConvertUtil.convertToString(paraMap.get("projectname"));
        long planid = ConvertUtil.convertToLong(paraMap.get("planid") );
        StringBufferProxy sql = new StringBufferProxy();
        GpmProjectPlanEntity gpmProjectPlanEntity = gpmProjectPlanService.queryById(ConvertUtil.convertToString(planid));
        if (!StringUtil.isEmpty(ids)) {
            StringBufferProxy sqlForMilepost = new StringBufferProxy();
            sqlForMilepost.appendSingle(" id in ({0}) order by sortcode ",ids);
            List<GpmMilePostTemplateEntity> sdMilePostTemplateEntities = gpmMilePostTemplateService
                    .queryByWhere(sqlForMilepost.toString());
            for (GpmMilePostTemplateEntity gpmMilePostTemplateEntity : sdMilePostTemplateEntities) {
                GpmProjectMilepostEntity gpmProjectMilepostEntity = new GpmProjectMilepostEntity();

                //赋值里程碑初始字段
                gpmProjectMilepostEntity.setId(0);
                gpmProjectMilepostEntity.setMilepostcode("0");
                gpmProjectMilepostEntity.setPlanfinishtime(null);
                gpmProjectMilepostEntity.setActualfinishtime(null);
                gpmProjectMilepostEntity.setMilepoststate(0);
                gpmProjectMilepostEntity.setOperatecode(0);
                gpmProjectMilepostEntity.setSourcetype(GpmMilePostTemplateEntity.tableName);
                gpmProjectMilepostEntity.setResponsible("");
                gpmProjectMilepostEntity.setResponsiblecode("");
                gpmProjectMilepostEntity.setState(0);
                gpmProjectMilepostEntity.setNewadd(1);
                //赋值拷贝字段
                gpmProjectMilepostEntity.setMilepostname(gpmMilePostTemplateEntity.getName());
                gpmProjectMilepostEntity.setDeliverable(gpmMilePostTemplateEntity.getDeliverable());
                gpmProjectMilepostEntity.setProjectcode(projectcode);
                gpmProjectMilepostEntity.setSourceid(gpmMilePostTemplateEntity.getId());
                gpmProjectMilepostEntity.setPlanid(planid);
                //新增
                gpmProjectMilepostEntity.setDeptcommoncode1(gpmProjectPlanEntity.getDeptcommoncode1());
                gpmProjectMilepostEntity.setProjectid(ConvertUtil.convertToLong(gpmProjectPlanEntity.getProjectid()));
                this.insert(gpmProjectMilepostEntity);
                sql.clear();
                sql.appendSingle("MILEPOSTTEMPLATEID = '{0}' order by sortcode ", gpmMilePostTemplateEntity.getId());
                List<GpmProjectTaskTemplateEntity> sdProjectTaskTemplateEntities = gpmProjectTaskTemplateService.queryByWhere(sql.toString());
                List<BasicEntity> projectTaskIns = new ArrayList<BasicEntity>();
                int index = 1;
                for(GpmProjectTaskTemplateEntity projectTaskTemplateEntity : sdProjectTaskTemplateEntities) {
                	GpmProjectTaskEntity gpmProjectTaskEntity = new GpmProjectTaskEntity();
                	gpmProjectTaskEntity.setTaskname(projectTaskTemplateEntity.getTaskname());
                	gpmProjectTaskEntity.setTaskdetail(projectTaskTemplateEntity.getTaskdetail());
                	gpmProjectTaskEntity.setState(0);
                	gpmProjectTaskEntity.setProjectcode(gpmProjectMilepostEntity.getProjectcode());
                    gpmProjectTaskEntity.setProjectname(projectname);
                	gpmProjectTaskEntity.setMilepostcode(ConvertUtil.convertToString(gpmProjectMilepostEntity.getOperatecode()));
                	gpmProjectTaskEntity.setMilepostname(gpmProjectMilepostEntity.getMilepostname());
                	gpmProjectTaskEntity.setTaskstate("0");
    				gpmProjectTaskEntity.setApplyorgcode(this.getSessionUserBean().getOrg().getCode());
    				gpmProjectTaskEntity.setApplydeptcode(this.getSessionUserBean().getDept().getCode());
    				gpmProjectTaskEntity.setOrgcode(this.getSessionUserBean().getOrg().getCode());
    				gpmProjectTaskEntity.setDeptcode(this.getSessionUserBean().getDept().getCode());
    				gpmProjectTaskEntity.setUsercode(this.getSessionUserBean().getUser().getCode());
    				gpmProjectTaskEntity.setUsername(this.getSessionUserBean().getUser().getName());
    				gpmProjectTaskEntity.setApplyusercode(this.getSessionUserBean().getUser().getCode());
    				gpmProjectTaskEntity.setApplyusername(this.getSessionUserBean().getUser().getName());
    				gpmProjectTaskEntity.setTaskcode(ConvertUtil.convertToString(gpmProjectMilepostEntity.getSortcode()+"-"+index));
    				//新增
    				gpmProjectTaskEntity.setDeptcommoncode1(gpmProjectPlanEntity.getDeptcommoncode1());
    				gpmProjectTaskEntity.setProjectid(ConvertUtil.convertToLong(gpmProjectPlanEntity.getProjectid()));
    				gpmProjectTaskEntity.setProjectname(gpmProjectPlanEntity.getProjectname());
    				index++;
                    projectTaskIns.add(gpmProjectTaskEntity);
                }
                gpmProjectTaskService.insertBatch(projectTaskIns);
            }
            return ResponseResult.ok("插入里程碑成功，共 " + sdMilePostTemplateEntities.size() + "条。");
        } else {
            return ResponseResult.ok("没有可插入的里程碑数据，请确认勾选相关里程碑！");
        }
    }
    /**
      * @description:
      * @author hdy
      * @param
      * @throws
      * @return
      * @date 2021-12-20
      * @modify
      */
    public List<Map<String,Object>> queryTaskListByType(String projectcode,String type){
        StringBufferProxy sql = new StringBufferProxy();
        //获取最新策划书
        sql.appendSingle("enabled=1 and state !=0  and projectcode ='{0}' order by CREATEON desc",projectcode);
        if(!gpmProjectPlanService.queryByWhere(sql.toString()).isEmpty()){
            //获取所有里程碑
            GpmProjectPlanEntity planEntity = gpmProjectPlanService.queryByWhere(sql.toString()).get(0);
            List<GpmProjectMilepostEntity> milePostList = this.queryByWhere(" "+ GpmProjectMilepostEntity.FieldPlanid+" = '"+planEntity.getId()+"' ");
            List<Map<String,Object>> taskList = new ArrayList<>();
            //只获取特定类型 的里程碑
            milePostList.stream().filter(milepost->{
              GpmMilePostTemplateEntity template = gpmMilePostTemplateService.queryById(ConvertUtil.convertToString(milepost.getSourceid()));
//                return  template !=null && template.getType().contentEquals(type);
                return  template !=null;
            }).forEach(milepost->{
                //获取里程碑下所有任务
              if(gpmProjectTaskService.queryByWhere(" "+ GpmProjectTaskEntity.FieldMilepostcode+" = '"+milepost.getId()+"' ")!=null)
              gpmProjectTaskService.queryByWhere(" "+ GpmProjectTaskEntity.FieldMilepostcode+" = '"+milepost.getId()+"' ")
                      .stream().forEach(task->{
                          //添加交付成果 里程碑名字 展示字段
                          Map<String, Object> taskmap = task.convertToMap();
                          if(ConvertUtil.convertToString(taskmap.get("taskschedule"))!=null)
                          taskmap.replace("taskschedule",ConvertUtil.convertToString(taskmap.get("taskschedule")).contentEquals("100")?"已完成":"未完成");
                          taskmap.put("milepostname",milepost.getMilepostname());
                          taskmap.put("deliverable",milepost.getDeliverable());
                  taskList.add(taskmap);
              });
            });
         return taskList;
        }else{
            return null;
        }
    }
    /**
     * @author houyuhang
     * @Description 首页里程碑超期
     * @Date 2021/11/29
     * @return Map<String,Object>
     **/
    @Override
    public Map<String,Object> queryOverdueMilepost(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        Map<String, Object> overdueMilepostResult = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateFormat = simpleDateFormat.format(new Date());
        // 查询未完成且已超期的里程碑
        sql.appendSingle(" GpmProjectMilepost.PLANFINISHTIME< {0} and " +
                "GpmProjectMilepost.MILEPOSTSTATE = '{1}' and GpmProjectMilepost.enabled = 1 ",
                SQLAdapter.toDateShort(dateFormat), GpmSystemConst.MilepostStateCode.MilepostIncompleteCode);
        sql.appendSingle(" and {0} ", gpmProjectService.whereExistsSqlForIndex(GpmProjectMilepostEntity.tableName,
                GpmProjectMilepostEntity.FieldProjectid, ConvertUtil.convertToString(paraMap.get("dataPermissionFlag"))));
        int countMilpost = this.getCount(sql.toString());
        overdueMilepostResult.put("code", "overdueMilepostNum");
        overdueMilepostResult.put("name", "超期里程碑");
        overdueMilepostResult.put("iconImg", "/static/images/paojectManager/overdueMilepostFlag.png");
        overdueMilepostResult.put("value", countMilpost);
        return overdueMilepostResult;
    }

    /**
     * @author zhangjunyao
     * @Description 联表查询督办情况（项目监管页面用）
     * @Date 2021/12/13
     * @return
     **/
    @Transactional
    public void getSuperviseList(List<Map<String, Object>> tempList) {
        // 查询的里程碑只属于一个项目
        String projectCode = ConvertUtil.convertToString(tempList.get(0).get("projectid"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("projectid = '{0}' and {1} = '2'", projectCode, GpmProjectSuperviseEntity.FieldSuperviseobjecttype);
        List<Map<String, Object>> superviseList = gpmProjectSuperviseService.queryMapByWhere(sql.toString());
        Map<String, List<Map<String, Object>>> superviseMapByMilepost = superviseList.stream().collect(Collectors.groupingBy(map ->
                ConvertUtil.convertToString(map.get(GpmProjectSuperviseEntity.FieldSuperviseobject))));
        for (Map<String, Object> mapRow : tempList) {
            String milepostName = ConvertUtil.convertToString(mapRow.get(GpmProjectMilepostEntity.FieldMilepostname));
            if (superviseMapByMilepost.containsKey(milepostName)) {
                mapRow.put("superviselist", superviseMapByMilepost.get(milepostName));
            }
        }
    }

    /**
     * @author zhangjunyao
     * @Description 联表查询里程碑项目相关信息（超期里程碑用）
     * @Date 2021/12/14
     * @return
     **/
    @Transactional
    public void getProjectInfo(List<Map<String, Object>> tempList) {
        String projectCodes = tempList.stream().map(map -> ConvertUtil.convertToString(map.get("projectcode")))
                .collect(Collectors.joining("','", "'", "'"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("projectcode in ({0})", projectCodes);
        List<GpmProjectEntity> projectEntities = gpmProjectService.queryByWhere(sql.toString());
        if (CollectionUtils.isEmpty(projectEntities)) {
            return;
        }
        Map<String, GpmProjectEntity> resultMap = projectEntities.stream().collect(Collectors.toMap(
                GpmProjectEntity::getProjectcode, sdProjectEntity -> sdProjectEntity));
        for (Map<String, Object> mapRow : tempList) {
            String projectCode = ConvertUtil.convertToString(mapRow.get("projectcode"));
            if (resultMap.containsKey(projectCode)) {
                GpmProjectEntity gpmProjectEntity = resultMap.get(projectCode);
                mapRow.put("projectname", gpmProjectEntity.getProjectname());
                mapRow.put("deptname", gpmProjectEntity.getDeptname());
                String projectlevel = gpmProjectEntity.getProjectlevel();
                mapRow.put("dispprojectlevel", datacodeCache.getValueDynamic("GpmProjectLevel", projectlevel,
                        "code", "name"));
                mapRow.put("projectmanager", gpmProjectEntity.getProjectmanager());
            }
        }
    }

    /**
     * @author zhangjunyao
     * @Description 联表查询里程碑未完成任务（超期里程碑用）
     * @Date 2021/12/14
     * @return
     **/
    @Transactional
    public void getUnfinishedTask(List<Map<String, Object>> tempList) {
        String milepostIds = tempList.stream().map(map -> ConvertUtil.convertToString(map.get("id")))
                .collect(Collectors.joining("','", "'", "'"));
        StringBufferProxy sql = new StringBufferProxy();
        // 获取创建时间最早的未完成任务（处于未开始、进行中、冻结状态的任务），按创建时间倒序排序
        sql.appendSingle("milepostcode in ({0}) and taskstate in (0,1,-1) and enabled = 1 order by createon desc", milepostIds);
        List<GpmProjectTaskEntity> taskEntities = gpmProjectTaskService.queryByWhere(sql.toString());
        if (CollectionUtils.isEmpty(taskEntities)) {
            for (Map<String, Object> mapRow : tempList) {
                mapRow.put("unfinishedtask", "暂无未完成的任务");
            }
            return;
        }
        Map<String, List<GpmProjectTaskEntity>> resultMap = taskEntities.stream().collect(Collectors.groupingBy(
                entity -> entity.getMilepostcode()));
        for (Map<String, Object> mapRow : tempList) {
            String milepostId = ConvertUtil.convertToString(mapRow.get(GpmProjectMilepostEntity.FieldId));
            if (resultMap.containsKey(milepostId)) {
                List<GpmProjectTaskEntity> sdProjectTaskEntities = resultMap.get(milepostId);
                // 获取创建时间最早的未完成任务
                mapRow.put("unfinishedtask", sdProjectTaskEntities.get(0).getTaskname());
            } else {
                mapRow.put("unfinishedtask", "暂无未完成的任务");
            }
        }
    }
    /**
     * @author houyuhang
     * @Description 获取里程碑超期天数（超期里程碑用）
     * @Date 2022/03/16
     * @return
     * @param tempList*/
    @Override
    @Transactional
    public void getMilepostOverdueDate(List<Map<String, Object>> tempList) {
        for (Map<String, Object> temp : tempList) {
            Date planFinishDate = ConvertUtil.convertToDate(temp.get("planfinishtime"));
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());
            long time1 = cal.getTimeInMillis();
            cal.setTime(planFinishDate);
            long time2 = cal.getTimeInMillis();
            long betweenDays = (time1-time2)/(1000*3600*24);
            temp.put("overdueday", Integer.parseInt(String.valueOf(betweenDays)));
        }
    }
    /**
     * @Title:
     * @description: 任务下发完成后给里程碑责任人发送消息提醒
     * @param
     * @return
     * @author: zhangjunyao
     * @date: 2021年12月14日
     * @modify:
     */
    @Transactional(rollbackFor = Exception.class)
    public void sendMessageToMilepostResponsible(String milepostCodes) {
        log.info("策划审批通过后,给里程碑负责人发送消息提醒");
        // 无任务下发时，milepostCodes为空，直接返回
        if (milepostCodes.equals("")) {
            return;
        }
        // 查询该策划书下所有里程碑
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" {0} in ({1}) and {2} = 1 ", GpmProjectMilepostEntity.FieldOperatecode, milepostCodes, GpmProjectMilepostEntity.FieldEnabled);
        List<GpmProjectMilepostEntity> sdProjectMilepostEntities = this.queryByWhere(sql.toString());
        if (CollectionUtil.isEmpty(sdProjectMilepostEntities)) {
            return;
        }
        // 查询该项目立项信息
        sql.clear();
        sql.appendSingle(" {0} = '{1}' ", GpmProjectEntity.FieldProjectcode, sdProjectMilepostEntities.get(0).getProjectcode());
        GpmProjectEntity gpmProjectEntity = gpmProjectService.queryObjectByWhere(sql.toString());
        if (ObjectUtil.isEmpty(gpmProjectEntity)) {
            return;
        }
        // 配置消息标题内容
        String projectLevel = datacodeCache.getValueDynamic("GpmProjectLevel", gpmProjectEntity.getProjectlevel(), "code", "name");
        String title = "通用项目任务下发提醒";
        StringBufferProxy contentTitle = new StringBufferProxy();
        contentTitle.appendSingle("【{0} {1}级 {2}】", gpmProjectEntity.getProjectcode(), projectLevel, gpmProjectEntity.getProjectname());
        String contentBody = "里程碑下的所有任务都已下发。";
        // 用于封装消息，批量插入
        List<Map<String, Object>> appList = new ArrayList<>(), sysList = new ArrayList<>();
        Map<String, Object> appMap = new HashMap<>(), sysMap = new HashMap<>();
        for(GpmProjectMilepostEntity gpmProjectMilepostEntity : sdProjectMilepostEntities) {
            // 获取任务名称，封装消息内容
            StringBufferProxy content = new StringBufferProxy();
            content.appendSingle("{0} “{1}”{2}", contentTitle.toString(), gpmProjectMilepostEntity.getMilepostname(), contentBody);
            // app推送
            appMap = MessageUtil.createMessageAppMapV1(gpmProjectMilepostEntity.getResponsiblecode(), gpmProjectMilepostEntity.getResponsible(), title, content.toString(), gpmProjectEntity.getId(),
                    GpmProjectMilepostEntity.tableName, 0);
            appMap.put("messagetype", MisSystemConst.MobileMessageType.OTHER_TYPE);
            // 系统消息
            sysMap = MessageUtil.createMessageSysMapV1(gpmProjectMilepostEntity.getResponsiblecode(), gpmProjectMilepostEntity.getResponsible(), title, content.toString(),
                    gpmProjectEntity.getId(), GpmProjectMilepostEntity.tableName);
            sysMap.put("messagetype", MisSystemConst.MobileMessageType.OTHER_TYPE);
            // 封装
            appList.add(appMap);
            sysList.add(sysMap);
        }
        // 消息批量插入
//        cboMessageAppService.insertList(appList);
//        cboMessageSysService.insertList(sysList);
        sendMessageService.sendSysMessage(sysList);
        sendMessageService.sendAppMessage(appList);
    }
}
